"""
获取发票信息接口
"""
import os
from flask import request, jsonify, Blueprint
from inv_parser.parser import do_parse
from inv_parser.logger import get_logger
from datetime import datetime as dt
from app.models import InvBase
from app.utils import get_filehash, allowed_file_extension
from config import Config

bp = Blueprint('app', __name__)
config = Config()
logger = get_logger('INFO', save_path=__file__)


@bp.route('/inv-base-info', methods=['POST'])
def parse_inv_file():
    username = request.form.get('username', 'default')
    file_storage = request.files.get('file')
    if not file_storage:
        return jsonify({'status_code': 3001, 'message': '没有接收到有效的文件数据！'})
    file_name = file_storage.filename
    if not allowed_file_extension(file_name):
        return jsonify({'status_code': 4001, 'message': '无效的文件类型！仅允许.pdf/.PDF/.png/.jpg/.jpeg/.bmp', 'file_name': file_name})
    user_dir = os.path.join(config.upload_dir, username, str(dt.now().date()))
    if not os.path.isdir(user_dir):
        os.makedirs(user_dir)
    path = os.path.join(user_dir, file_name)
    try:
        file_storage.save(path)
        inv_data = InvBase.exists(path)
        if inv_data is not None:
            return jsonify({'status_code': 1002, 'message': '文件已存在', 'data': inv_data})
        else:
            state, msg, _, result, source = do_parse(path)
            inv_data = {"username": username, "path": path, "filehash": get_filehash(path), 
                        "message": msg, "source": source}
            if not state:
                result = ['', '', '', '', '']
            inv_data.update({"inv_code": result[0], "inv_num": result[1], "inv_date": result[2], "inv_chk": result[3], "inv_money": result[4]})
            inv = InvBase.from_dict(inv_data)
            return jsonify({'status_code': 1001, 'message': '解析成功', 'data': inv.to_dict()})
    except Exception as e:
        return jsonify({'status_code': 5001, 'message': str(e)})
